<template>
    <div class="left-center">
        <div class="behavior-identify">
            <div class="check-title"><span class="title-info">行为识别</span></div>
            <div class="check-content">
                <div ref="main" class="interior"></div>
            </div>
        </div>
    </div>

</template>
<script setup>
import {wsUrl} from "../utlis/requests"
import * as echarts from 'echarts';
import { ref, onMounted,onUnmounted,nextTick} from "vue"
const totals=ref(0)
let ws=null;
let reconnectTimeout = null; // 重连超时控制
const main = ref()
let myChart=null;
const datas=ref([
    {value:0,name:'老鼠活动'},
    {value:0,name:'火焰识别'},
    {value:0,name:'口罩识别'},
    {value:0,name:'抽烟识别'},
    {value:0,name:'明火离岗'},
    {value:0,name:'帽子识别'},
    {value:0,name:'夜间人员闯入'},
    {value:0,name:'设备自检'}
])




// 建立 WebSocket 连接
const connectWebSocket = () => {
    ws = new WebSocket(wsUrl); // 替换为实际的 WebSocket 服务 URL
    ws.onopen = () => {
        console.log("WebSocket 连接已建立");
    };

    ws.onmessage = (event) => {
        //console.log('eee',event.data)
        if(event.data!='Connected'){
            let result=JSON.parse(event.data)
             console.log('datas',result)
            // console.log('datas.type',result.type)
            //const option = myChart.getOption(); // 获取当前配置项
            if(result.type=='alarmInfo'){
                let res=result.content;

                const changeData=datas.value.map(item=>{
                    const findItem=res.find(ritem=>ritem.ename==item.name)
                    console.log('findItem',findItem)
                    if(findItem){
                        item.value=findItem.count
                    }else{
                        item.value=0
                    }
                    return item
                })
                const totalValues = changeData.reduce((total, item) => total + item.value, 0);
                //nextTick(()=>{
                    myChart.setOption({ 
                        series: [{
                            data: changeData
                         }],
                         title:{
                          subtext:totalValues+'', 
                        } 
                    })
                //})
            }else{
                //nextTick(()=>{
                    myChart.setOption({ 
                        series: [{
                            data: datas.value
                        }],
                        title:{
                          subtext:totals.value+'', 
                        }
                    })
                    //setecharts();
                //})
            }
        }
    };
    ws.onerror = (error) => {
        console.error("WebSocket 发生错误", error);
    };

    ws.onclose = (event) => {
    //console.log("WebSocket 连接已关闭", event.code);
    handleReconnect(); // WebSocket 连接关闭时尝试重连
    };
};
// 处理 WebSocket 连接断开后的重连
const handleReconnect = () => {
    // 如果已经在重连，避免重复重连
    if (reconnectTimeout) {
    return;
    }

    reconnectTimeout = setTimeout(() => {
    //console.log("正在尝试重新连接 WebSocket...");
    connectWebSocket();
    reconnectTimeout = null; // 重连后清除重连超时
    }, 5000); // 5 秒后重连
};

const setecharts = () => {
    myChart = echarts.init(main.value)
    let option = {
        title:{
            text:'总数量',
            subtext:totals.value+'',
            itemGap:10,
            x:'center',
            y:'cetnter',
            left: '23%',
            top: '40%',
            textAlign:'center',
            textStyle:{
                fontSize:'20',
                color:'#fff',
                fontWeight:'400',
                fontFamily: "Microsoft YaHei"
            },
            subtextStyle:{
                fontSize:'16',
                fontWeight:'400',
                color:'#fff'
            }
        },
        tooltip: {
            trigger: 'item',
            formatter: "{a} <br/>{b}: {c} ({d}%)"
        },
        grid: {
            //设置图表撑满整个画布
            top: '50%', // 可以根据需要调整这个值来控制距离顶部的距离
            bottom: '20%' // 同理，根据需要调整这个值来控制距离底部的距离
        },
        legend: {
            right: 'right',
            top: 'center',
            orient: 'vertical',
            itemWidth: 10,
            itemHeight: 10,
            //itemGap: 10,
            icon:'circle',
            height:'100%',
            formatter(name) {
                   var data = datas.value;//获取series中的data
                   var total = 0;
                   var tarValue;
                   for (var i = 0, l = data.length; i < l; i++) {
                       total += data[i].value;
                       if (data[i].name == name) {
                           tarValue = data[i].value;
                       }
                   }
                   //console.log('total',total)
                   var percent = tarValue?((tarValue / total) * 100).toFixed(2):0;
                   let arr = ['{a|' + name + '}', '{c|' + percent + '%}','{b|' + tarValue + '}'+'\n{d|}'] 
                   return arr.join('');
            },
            textStyle: {
              color: '#fff',  // 图例文字颜色
              fontSize:15,
              rich:{
                d: {   
                    width: '100%',
                    borderWidth: 0.5,
                    height:1,
                    backgroundColor: '1',
                },
                a: {
                    width: 100,
                    align: 'left',
                    fontSize:14,
                    //color:'1',
                },
                b: {
                    width: 60,
                    align: 'center',
                    fontSize:14,
                    //color:'1'
                },
                c:{
                    width: 60,
                    align: 'center',
                    fontSize:14,
                    //color:'1'
                }
              }
            },
        },
        color:['#5470c6','#91cc75','#fac858','#ee6666','#73c0de','#a6cbff','#3ba272'],
        series: [
                {
                name: '行为识别',
                type: 'pie',
                radius: ['60%', '80%'],
                center:['24.6%','50%'],
                avoidLabelOverlap: false,
                label: {
                    show: false,
                    position: 'center'
                },
                labelLine: {
                    show: false
                },
                data:datas.value
            }
        ],
        graphic: {
          //设置中心图片及文字
          elements: [
            {
              type: "image", //通过不同top值可以设置上下显示
              left: "left",
              top: '4%',
              style: {
                image: require("@/components/img/preview.png"), // 添加你想要展示的图片的URL
                width: 250,
                height: 220,
                top: "center", // 图片距离容器顶部的距离
              }
              
            },
            // {
            //   type: "text", //通过不同top值可以设置上下显示
            //   left: '19%', // 居中显示
            //   top: 'center', // 居中显示
            //   style: {
            //         text: '总数量', // 文本内容
            //         textBaseline: 'middle',
            //         textAlign: 'center',
            //         fill: '#fff', // 文本颜色
            //         fontSize: 16 // 文本大小
            //     }
            // }
          ]
        },
    }
    option && myChart.setOption(option);
}

onMounted(() => {
    connectWebSocket(); // 组件加载时连接 WebSocket
    setTimeout(()=>{
        setecharts()
    },1000)
    
})

onUnmounted(() => {
    if (ws) {
        ws.close();
    }
    if (myChart) {
        myChart.dispose(); // 组件卸载时销毁实例
    }
});

</script>

<style scoped lang="less">
.left-center{
    height:304px;
    width:548px;
    background: url('../components/img/behavior-bg.png') no-repeat;
    background-size: 100% 100%;
    margin-bottom:20px;
    transform: matrix(1, 0, 0, 1, 1, 0);
    transition-duration: 0ms;
}
:deep(canvas){
    top:-5px;
}
.behavior-identify{
    padding:15px 20px;
    display:flex;
    flex-direction:column;
    height:100%;
    .check-title{
        color:#fff;
        background: url('../components/img/title-bg.png') no-repeat;
        background-size: 100% 100%;
        height:36px;
        line-height:36px;
        .title-info{
            margin-left:40px;
        }
    }
    .check-content{
        display: flex;
        align-items:center;
        justify-content: space-between;
        height:calc(100% - 36px);
        .interior{
            width:100%;
            height: 100%;
        }
    }
    
}
</style>